多个单文件组件使用

在project目录下创建components文件夹,然后将所有子组件放入components文件夹下Snip20190404_2

1、多组件嵌套使用

Child1.vue

<template>
    <div>子组件1div>
template>

<script>
// export default {

// }
script>

<style>

style>

Child2.vue

<template>
    <div>子组件2div>
template>

<script>
// export default {

// }
script>

<style>

style>

App.vue

<template>
    <div>
        单文件组件
        
        <Child1>Child1>
        <Child2>Child2>
    div>

template>


<script>
    //导入components目录下的子文件 Child1为指定的组件名,可以任意命名,不一定按照文件名
import Child1 from './components/Child1.vue'
import Child2 from './components/Child2.vue'

export default {
    // 将子组件添加到App.vue中
    components:{
        Child1,
        Child2,

    }
}
script>

<style>

style>

2、多组件路由使用

使用路由形式将多个单文件组件组合在一起

  1. 定义路由目录和路由文件

    mkdir router
    touch router.js
    
  2. 编写路由文件router.js

    1. import Vue from 'vue'
      // 导入路由插件
      import Router from 'vue-router'
      import Child1 from '../components/Child1.vue'
      import Child2 from '../components/Child2.vue'
      // 在vue中使用插件
      Vue.use(Router)
      export default new Router({
          // 定义匹配规则
         routes:[
             {
                 path:'/',  // 匹配根路径/,加载Chiled1中的内容
                 component:Child1
             },
             {
                 path:'/child2',
                 component:Child2
             }
         ]
      })
      
  3. 在main.js中使用路由

    1. import Vue from 'vue'
      import App from './App.vue'
      //导入定义好的路由
      import router from './router/router.js'
      
      new Vue({
          el:'#app',
          router,  //使用路由
          render:function(creater){
              return creater(App)
          }
      })
      
  4. 在App.vue中指定路由标签

    1. <template>
          <div>
              单文件组件
               
              <router-view>router-view>
          div>
      
      template>
      
      <script>
      script>
      
      <style>
      style>
      
powered by GitbookFile Modify: 2019-04-04 20:08:03